package notifier

import (
	"github.com/blinkbean/dingtalk"
	"go-learn/go_learn/prometheus/web_hook/pkg/setting"

	"go-learn/go_learn/prometheus/web_hook/global"
	"go-learn/go_learn/prometheus/web_hook/model"
	"go-learn/go_learn/prometheus/web_hook/transformer"
)

// Send send markdown message to dingtalk
func Send(notification model.Notification) (err error) {
	notifyData, err := transformer.TransformToMarkdown(notification)
	if err != nil {
		return
	}

	notifyMap := handleNotifyData(notifyData)
	for _, v := range notifyMap {
		token, secret, atMobiles := getRobotParam(v.RobotName)

		dingtalkCli := dingtalk.InitDingTalkWithSecret(token, secret)
		dingtalkCli.SendMarkDownMessage(v.Title, v.Content, dingtalk.WithAtMobiles(atMobiles))
	}

	return
}

// convertRobotConfToMap
func convertRobotConfToMap() (res setting.RobotMap) {
	robotCfg := global.Robot
	res = make(map[string]setting.RobotConf, 0)

	for _, v := range *robotCfg {
		alertName := v.AlertName

		res[alertName] = v
	}

	return
}

func getRobotParam(alertName string) (token, secret string, atMobiles []string) {
	robotCfgMap := convertRobotConfToMap()

	if cfg, ok := robotCfgMap[alertName]; ok {
		token = cfg.Token
		secret = cfg.Secret
		atMobiles = cfg.AtMobiles
	} else {
		defaultRobot := global.DefaultRobot
		token = defaultRobot.Token
		secret = defaultRobot.Secret
		atMobiles = defaultRobot.AtMobiles
	}

	return
}

// handleNotifyData 聚合发送给同一个机器人的数据，一个机器人只发一条消息
func handleNotifyData(data model.NotifyData) (res model.NotifyMap) {
	res = make(map[string]*model.Notify, 0)

	for _, v := range data {
		robotName := v.RobotName
		if _, ok := res[robotName]; ok {
			notify := res[robotName]
			notify.Content += v.Content
			res[robotName] = notify
		} else {
			notify := &model.Notify{
				RobotName: robotName,
				Title:     v.Title,
				Content:   v.Content,
			}
			res[robotName] = notify
		}
	}

	return
}
